package com.lh.learning.activiti.controller;

import io.swagger.annotations.ApiOperation;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.DeploymentBuilder;
import org.activiti.engine.repository.ProcessDefinition;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.zip.ZipInputStream;

/**
 * Created by lh on 2018/6/20.
 */
@RestController
@RequestMapping("/workflow")
public class ActivitiController {

    @Autowired
    private RepositoryService repositoryService;

    @ApiOperation("流程定义列表")
    @GetMapping("/process/list")
    public List<Object> processList() {
        List<Object> list = repositoryService.createProcessDefinitionQuery().list()
                .stream()
                .map(processDefinition -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", processDefinition.getId());
                    map.put("key", processDefinition.getKey());
                    map.put("name", processDefinition.getName());
                    map.put("category", processDefinition.getCategory());
                    map.put("deploymentId", processDefinition.getDeploymentId());
                    map.put("description", processDefinition.getDescription());
                    map.put("diagramResourceName", processDefinition.getDiagramResourceName());
                    map.put("resourceName", processDefinition.getResourceName());
                    map.put("tenantId", processDefinition.getTenantId());
                    map.put("version", processDefinition.getVersion());
                    return map;
                }).collect(Collectors.toList());
        return list;
    }

    @ApiOperation("部署流程")
    @PostMapping("/deploy/process")
    public String deployProcess(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        try {
            InputStream inputStream = file.getInputStream();
            String extension = FilenameUtils.getExtension(fileName);
            DeploymentBuilder deployment = repositoryService.createDeployment();
            if (extension.equals("zip") || extension.equals("bar")) {
                ZipInputStream zipInputStream = new ZipInputStream(inputStream);
                deployment.addZipInputStream(zipInputStream);
            } else {
                deployment.addInputStream(fileName, inputStream);
            }
            deployment.deploy();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "success";
    }

    @ApiOperation("读取流程定义的XML")
    @GetMapping("/resource")
    public void getResource(String processDefinitionId, String resourceName, HttpServletResponse response) throws IOException {
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .processDefinitionId(processDefinitionId).singleResult();
        InputStream inputStream = repositoryService.getResourceAsStream(processDefinition.getDeploymentId(), resourceName);

        byte[] bytes = new byte[1024];
        int len;
        while ((len = inputStream.read(bytes, 0, 1024)) != -1) {
            response.getOutputStream().write(bytes, 0, len);
        }
    }

    @ApiOperation("删除部署")
    @PostMapping("/delete/deployment")
    public String deleteDeployment(String deploymentId) {
        repositoryService.deleteDeployment(deploymentId,true);
        return "success";
    }
}
